import router from './routers'
import { resetRouter } from './routers'
import store from '@/store'
import Config from '@/settings'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
import { getToken } from '@/utils/auth' // getToken from cookie
import { buildMenus, getRouterList } from '@/api/system/menu'
import { getRouterMenuList } from '@/api/login'
import { filterAsyncRouter } from '@/store/modules/permission'

import { constantRouterMap } from '@/router/routers'
// import Router from 'vue-router'

import i18n from '@/locale'
import Cookies from 'js-cookie'
NProgress.configure({ showSpinner: false })// NProgress Configuration

const whiteList = ['/login']// no redirect whitelist

router.beforeEach((to, from, next) => {
  if (to.meta.title) {
    document.title = i18n.t(to.meta.title) + ' - ' + Config.title
  }
  NProgress.start()
  if (getToken()) {
    // 已登录且要跳转的页面是登录页
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
        store.dispatch('GetInfo').then(() => { // 拉取user_info
          // 动态路由，拉取菜单
          // loadMenus(next, to)
          // getMenusList(next, to)
          changeRouter(next, to)
          // 获取产品目录
          getRouterMenu()
        }).catch(() => {
          store.dispatch('LogOut').then(() => {
            location.reload() // 为了重新实例化vue-router对象 避免bug
          })
        })
      } else if (store.getters.loadMenus) {
        // 登陆成功之后会做的操作
        // 修改成false，防止死循环
        store.dispatch('updateLoadMenus')
        // loadMenus(next, to)
        // getMenusList(next, to)
        // 获取产品目录
        getRouterMenu()
        changeRouter(next, to)
      } else {
        // 每次切换路由避免再次请求没必要的路由接口 如果路由长度大于默认长度,则代表已经请求过路由数据,不需要再次请求,直接 next
        if (store.state.permission.routers.length > constantRouterMap.length) {
          next()
        } else {
          changeRouter(next)
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})
// 有空再搞
// router.onReady((res) => {
//   console.log('路由初始化成功')
// }, (rej) => {
//   console.log('路由初始化成失败')
// })

export const loadMenus = (next, to) => {
  buildMenus().then(res => {
    var routes = res.data
    const asyncRouter = filterAsyncRouter(routes)
    asyncRouter.push({ path: '*', redirect: '/dashboard', hidden: true })
    store.dispatch('GenerateRoutes', asyncRouter).then(() => { // 存储路由
      router.addRoutes(asyncRouter) // 动态添加可访问路由表
      next({ ...to, replace: true })
    })
  })
}
// export const getMenusList = (next, to) => {
//   const id = Cookies.get('routerMenu') || undefined
//   getRouterList({ id }).then(res => {
//     var routes = res.data
//     const asyncRouter = filterAsyncRouter(routes)
//     asyncRouter.push({ path: '*', redirect: '/dashboard', hidden: true })
//     store.dispatch('GenerateRoutes', asyncRouter).then(() => { // 存储路由
//       router.addRoutes(asyncRouter) // 动态添加可访问路由表
//       next({ ...to, replace: true })
//     })
//   })
// }

export const changeRouter = (next, to) => {
  resetRouter()
  const id = Cookies.get('routerMenu') || undefined
  getRouterList({ id }).then(res => {
    var routes = res.data
    const asyncRouter = filterAsyncRouter(routes)
    asyncRouter.push({ path: '*', redirect: '/dashboard', hidden: true })
    store.dispatch('GenerateRoutes', asyncRouter).then(() => { // 存储路由
      router.addRoutes(asyncRouter) // 动态添加可访问路由表
      next({ ...to, replace: true })
    })
  })
}

export const getRouterMenu = () => {
  getRouterMenuList().then(res => {
    store.dispatch('getRouterMenuList', res.data)
  })
}

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
